//
//  NetwokeManager.m
//  NSURLSession封装
//
//  Created by 周成龙 on 16/11/1.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "NetwokeManager.h"
#import "ZSessionHeader.h"

@interface NetwokeManager () <NSURLSessionDelegate>

@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSMutableData *dataM;
@property (nonatomic, copy) completeBlock completeBlock;

@end

@implementation NetwokeManager
//+ (instancetype)shareNetwokeManager {
//    static NetwokeManager *manager = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        manager = [[NetwokeManager alloc] init];
//    });
//    return manager;
//}

- (void)GetMethodURL:(NSString *)path parameters:(NSDictionary *)parameters uploadPreogerss:(void (^)(NSProgress *))progress complete:(completeBlock)completeBlock {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    request.HTTPMethod = @"GET";
    [self request:request parameters:parameters complete:completeBlock];
}

- (void)POSTMethodURL:(NSString *)path parameters:(NSDictionary *)parameters uploadPreogerss:(void (^)(NSProgress *))progress complete:(completeBlock)completeBlock {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    request.HTTPMethod = @"POST";
    [self request:request parameters:parameters complete:completeBlock];
}

- (void)request:(NSMutableURLRequest *)request parameters:(NSDictionary *)parameters complete:(completeBlock)completeBlock {
    _completeBlock = completeBlock;
    NSString *bodyString = [NSString JSONStringWithDiction:parameters];
    request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
    [task resume];
}

// 请求完成 / 失败 的时候调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    //解析服务器返回数据
//    NSLog(@"-1-%@", [[NSString alloc] initWithData:self.dataM encoding:NSUTF8StringEncoding]);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_completeBlock) {
            _completeBlock(self.dataM, error ? error:nil);
        }
    });
}

#pragma mark - NSURLSessionDataDelegate
// 接收 到服务器 响应 的时候调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    
    //子线程中执行
    NSLog(@"当前线程 --> %@", [NSThread currentThread]);
    
    self.dataM = [NSMutableData data];
    //默认情况下不接收数据
    //必须告诉系统是否接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}

// 接受 到服务器 返回 数据的时候调用,可能被调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    //拼接 服务器返回的 数据
    [self.dataM appendData:data];
}

- (void)dealloc {
    NSLog(@"dealloc");
}

@end
